import {
  queryProgram,
  queryProgType,
  removeProgram,
  addProgram,
  editProgram,
  publishRule,
  uploadRule,
  copyRule,
  addProgramMat,
  editProgramMat,
} from '../services/api';
import { message } from 'antd';
import moment from 'moment';
import update from 'immutability-helper';

function method(str, a, b) {
  let type = 'string';
  if (str === 'createTime') {
    type = 'date';
  } else if (str === 'progId') {
    type = 'num';
  }
  switch (type) {
    case 'num': // 数字排序
      return a - b;
    case 'date': // 日期排序，IE8下'2012-12-12'这种格式无法设置时间，替换成'/'
      return moment(a).unix() - moment(b).unix();
    default:
      // 字符串排序
      return a.localeCompare(b);
  }
}
export default {
  namespace: 'program',

  state: {
    list: [],
    pagination: {},
    progType: [],
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const response = yield call(queryProgram, payload);
      // //console.log('rule fetch', payload);
      let dataSource = response.programs;
      if (payload) {
        if (payload.sorter) {
          const s = payload.sorter.split('_');
          if (s[1] === 'descend') {
            dataSource = dataSource.sort((prev, next) => method(s[0], next[s[0]], prev[s[0]]));
          } else {
            dataSource = dataSource.sort((prev, next) => method(s[0], prev[s[0]], next[s[0]]));
          }
        }

        let pageSize = 10;
        if (payload.pageSize) {
          pageSize = payload.pageSize * 1;
        }

        const result = {
          list: dataSource,
          pagination: {
            total: response.pageInfo.pageTotal,
            pageSize,
            current: parseInt(payload.page, 10) || 1,
          },
        };
        yield put({
          type: 'save',
          payload: result,
        });
      }
    },

    *add({ payload, callback }, { call, put }) {
      const response = yield call(addProgram, payload);
      if (response?.result?.code === 2001) {
        message.error('添加出错，请检查');
      } else {
        yield put({
          type: 'addProgram',
          payload: response.createProgram,
        });
        if (callback) callback();
      }
    },

    *edit({ payload, callback }, { call, put }) {
      const response = yield call(editProgram, payload);
      if (response?.result?.code === 2001) {
        message.error('编辑出错，请检查');
      } else {
        yield put({
          type: 'editProgram',
          payload: response.editProgram,
        });
        if (callback) callback();
      }
    },
    *remove({ payload, callback }, { call, put }) {
      const { progIds } = payload;
      const newpayload = { progIds: progIds.join(',') };
      const response = yield call(removeProgram, newpayload);
      if (response?.result?.code === 2001) {
        message.error('删除出错，请检查');
      } else {
        yield put({
          type: 'removeProgram',
          payload: { progIds },
        });
        if (callback) callback();
      }
    },

    *addProgramMat({ payload, callback }, { call, put }) {
      const { jsonCont } = payload;
      const response = yield call(addProgramMat, { jsonCont: JSON.stringify(jsonCont) });
      //console.log('add mat respone', response);
      if (response?.result?.code === 2001) {
        message.error('提交出错，请检查');
      } else if (callback) callback();
    },


    *update({ payload, callback }, { call, put }) {
      const response = yield call(updateRule, payload);

      if (response.result.code === 1000) {
        notification.success({
          message: `更新成功`,
        });
      }
    },
    *publish({ payload, callback }, { call, put }) {
      const response = yield call(publishRule, payload);
      //if (callback) callback();
      //console.log('pulish result', response);
      if (response?.result?.code === 2001) {
        message.error({
          message: `发布失败,请联系管理员`,
        });
      } else if (callback) callback();
    },
    *copy({ payload, callback }, { call }) {
      const response = yield call(copyRule, payload);
      //console.log('copy result', response);
      if (response?.result?.code === 2001) {
        message.error({
          message: `复制失败,请联系管理员`,
        });
      } else if (callback) callback();
    },
    *fetchProgType({ payload, callback }, { call, put }) {
      const response = yield call(queryProgType, payload);
      if (response?.result?.code === 2001) {
        message.error('请求出错，请检查');
      } else {
        yield put({
          type: 'saveProgType',
          payload: response.progTypeCodes,
        });
        if (callback) callback();
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        list: action.payload.list,
        pagination: action.payload.pagination,
      };
    },
    saveProgType(state, action) {
      return {
        ...state,
        progType: action.payload,

      };
    },

    addProgram(state, action) {
      const newState = update(state, {
        list: {
          $splice: [[0, 0, action.payload]],
        },
      });
      return newState;
    },
    editProgram(state, action) {
      const index = state.list.findIndex(item => item.progId === action.payload.progId);
      const newitem = { ...action.payload, createTime: action.payload.updateTime };
      //console.log('edit index', index);
      const newState = update(state, {
        list: {
          $splice: [[index, 1, newitem]],
        },
      });
      return newState;
    },

    removeProgram(state, action) {
      const newlist = state.list.filter(item => action.payload.progIds.indexOf(item.progId) === -1);
      return {
        ...state,
        list: newlist,
      };
    },
  },
};
